/* eslint-disable react-hooks/rules-of-hooks */
import React, { forwardRef, useState, useRef, useImperativeHandle, useEffect } from 'react';
import styles from './style.less';
import { PageContainer } from '@ant-design/pro-layout';
import { EllipsisOutlined } from '@ant-design/icons';
import { ProColumns, ProTable, ProDescriptions } from '@ant-design/pro-components';
import { Button, Space, message, Popconfirm, Modal } from 'antd';
import { getListPage, getLogininfor, removeByIds } from '@/services/api/monitor/logininfor';
import { reject } from 'lodash';
import { buildParams, copyObj } from '@/utils/paramUtils';
import { tableSuppert } from '@/utils/response';

const stateValueEnum = {
  0: {
    text: '登录成功',
    status: 'Processing',
  },
  1: {
    text: '登录失败',
    status: 'Error',
  },
};

export default function logininfor() {
  // 列
  const columns = [
    {
      title: '#',
      dataIndex: 'index',
      valueType: 'indexBorder',
      hideInSearch: true,
      width: 48,
    },
    {
      title: '编号',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '登录用户名',
      dataIndex: 'username',
    },
    {
      title: '登录设备',
      dataIndex: 'sourceType',
    },
    {
      title: '操作系统',
      dataIndex: 'os',
    },
    {
      title: '登录IP',
      dataIndex: 'ipAddress',
    },
    {
      title: '登录地点',
      dataIndex: 'ipLocation',
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        1: {
          text: '登录失败',
          status: 'Error',
        },
        0: {
          text: '登录成功',
          status: 'Processing',
        },
      },
    },
    {
      title: '登录时间',
      dataIndex: 'loginTime',
      key: 'showTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '登录时间',
      dataIndex: 'loginTime',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            beginTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      key: 'action',
      hideInSearch: true,
      render: (text, record, index, action) => [
        <Space key="action">
          <a key="view" onClick={() => showView(record.id)}>
            查看
          </a>
          <Popconfirm
            title={() => '您确定要删除此条登录信息'}
            onConfirm={() => remove(record.id)}
            okText="Yes"
            cancelText="No"
          >
            <a key="delete">删除</a>
          </Popconfirm>
        </Space>,
      ],
    },
  ];
  // 删除操作
  const remove = (ids) => {
    removeByIds(ids).then((res) => {
      message.success(res.msg);
      // 刷新表格
      tableRef.current.reload();
    });
  };
  // 查看详情
  const showView = (id) => {
    setOpen(true);
    setId(id);
    setTimeout(() => {
      drawerRef.current.reloadDescriptions();
    });
  };
  //抽屉是否显示
  const [open, setOpen] = useState(false);
  // id值
  const [id, setId] = useState(0); //id
  // 子组件ref
  const drawerRef = useRef(null);
  // 表格ref
  const tableRef = useRef();
  const getList = async (param, sorter) => {
    // 为了解决重复发起请求问题
    let sort = copyObj(sorter);
    if (Object.keys(sort).length === 0) {
      sort.loginTime = 'desc';
    }
    const data = await getListPage(buildParams(param, sort)).then((res) => {
      return res.data;
    });
    return tableSuppert(data);
  };
  return (
    <PageContainer content="记录用户登录数据">
      <ProTable
        // actionRef={tableRef}
        // 聚焦加载 false
        revalidateOnFocus={false}
        // 等分每列
        tableLayout="fixed"
        // 分页配置
        pagination={{ defaultPageSize: 10, showQuickJumper: true }}
        // 表头
        columns={columns}
        // 发请求
        request={getList}
        // 选择
        rowSelection={{}}
        // 关键key
        rowKey="id"
        //开启搜索
        search={true}
        tableAlertOptionRender={({ selectedRowKeys }) => {
          return (
            <Space size={16}>
              <Popconfirm
                title={() => '您确定要删除这些登录信息'}
                onConfirm={() => remove(selectedRowKeys)}
                okText="Yes"
                cancelText="No"
              >
                <a>批量删除</a>
              </Popconfirm>

              <a>导出数据</a>
            </Space>
          );
        }}
      />
      <ShowDrawer ref={drawerRef} id={id} open={open} setOpen={setOpen.bind(this)} />
    </PageContainer>
  );
}

/**
 * 详情子组件
 */
const ShowDrawer = forwardRef((props, ref) => {
  const detilaRef = useRef();

  // 刷新Descriptions
  const reloadDescriptions = () => {
    detilaRef.current.reload();
  };
  // 绑定函数
  useImperativeHandle(ref, () => ({
    reloadDescriptions,
  }));

  // 关闭抽屉
  const closeDrawer = () => {
    props.setOpen(false);
  };
  // 查询详情
  const getDetials = async () => {
    return new Promise((resolve, reject) => {
      getLogininfor(props.id)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  return (
    <Modal title="登录详情" width={'45%'} open={props.open} onCancel={closeDrawer} footer={null}>
      <ProDescriptions
        actionRef={detilaRef}
        bordered={true}
        request={async () => {
          return await getDetials();
        }}
      >
        <ProDescriptions.Item dataIndex="id" label="编号" span="1.5" />
        <ProDescriptions.Item dataIndex="username" label="登录用户名" span="1.5" />
        <ProDescriptions.Item dataIndex="sourceType" label="登录设备" span="1.5" />
        <ProDescriptions.Item dataIndex="os" label="操作系统" span="1.5" />
        <ProDescriptions.Item
          dataIndex="status"
          label="登录状态"
          valueEnum={stateValueEnum}
          span="1.5"
        />
        <ProDescriptions.Item dataIndex="loginTime" label="登录时间" span="1.5" />
        <ProDescriptions.Item dataIndex="ipLocation" label="登录地点" span="1.5" />
        <ProDescriptions.Item dataIndex="message" label="返回消息" />
      </ProDescriptions>
    </Modal>
  );
});
